<?php namespace Phpcmf\Model\Comment;

// 评论插件
class Comment extends \Phpcmf\Model
{

    // 读取配置信息
    public function get_setting($name) {
        $data = $this->table('app_comment'.(SITE_ID>1 ? SITE_ID : ''))->where('name', $name)->getRow();
        return $data ? dr_string2array($data['value']) : [];
    }

    // 存储配置信息
    public function save_setting($name, $value) {
        $this->db->table('app_comment'.(SITE_ID>1 ? SITE_ID : ''))->replace([
            'name' => $name,
            'value' => dr_array2string($value),
        ]);
    }

    // 删除配置信息
    public function remove_setting($name) {
        $this->db->table('app_comment'.(SITE_ID>1 ? SITE_ID : ''))->where('name', $name)->delete();
    }

    // 模块里面卸载评论
    public function uninstall_module($dir, $siteid) {

        $module = $this->db->table('module')->where('dirname', $dir)->get()->getRowArray();
        if (!$module) {
            return dr_return_data(0, '模块['.$dir.']未安装');
        }
        // 删除评论
        $comment = require dr_get_app_dir('comment').'Config/Table.php';
        $module['site'] = dr_string2array($module['site']);
        foreach ($module['site'] as $sid => $t) {
            $table = $this->dbprefix(dr_module_table_prefix($dir, $sid)); // 当前表前缀
            foreach ($comment as $name => $sql) {
                $this->db->simpleQuery('DROP TABLE IF EXISTS `'.$table.$name.'`');
            }
        }

        $this->db->table('field')->where('relatedname', 'comment-module-'.$dir)->delete();
        $this->table('admin_menu')->like('mark', 'comment-verify-module-'.$dir)->delete();

        return dr_return_data(1, 'ok');
    }

    // 模块里面安装评论
    public function install_module($dir, $siteid) {

        $module = $this->db->table('module')->where('dirname', $dir)->get()->getRowArray();
        if (!$module) {
            return dr_return_data(0, '模块['.$dir.']未安装');
        }

        // 创建评论文件
        $path = dr_get_app_dir($dir).'Controllers/';
        $syspath = dr_get_app_dir('comment').'Code/';
        foreach (['Comment.php', 'Admin/Comment.php', 'Admin/Comment_verify.php'] as $file) {
            if (!is_file($path.$file)) {
                $code = file_get_contents($syspath.$file);
                if (!$code) {
                    return dr_return_data(0, '文件['.$syspath.$file.']读取失败');
                }
                $rt = file_put_contents($path.$file, $code);
                if (!$rt) {
                    return dr_return_data(0, '文件['.$path.$file.']不可写入，创建失败');
                }
            }
        }

        $module['site'] = dr_string2array($module['site']);

        //$cfg = '{"use":"1","num":"0","my":"0","reply":"0","ct_reply":"0","pagesize":"","pagesize_mobile":"","pagesize_api":"","review":{"score":"10","point":"0","value":{"1":{"name":"1星评价"},"2":{"name":"2星评价"},"3":{"name":"3星评价"},"4":{"name":"4星评价"},"5":{"name":"5星评价"}},"option":{"1":{"name":"选项1"},"2":{"name":"选项2"},"3":{"name":"选项3"},"4":{"name":"选项4"},"5":{"name":"选项5"},"6":{"name":"选项6"},"7":{"name":"选项7"},"8":{"name":"选项8"},"9":{"name":"选项9"}}}}';

        $table = $this->dbprefix(dr_module_table_prefix($dir, $siteid)); // 当前表前缀
        // 创建评论表
        $comment = require dr_get_app_dir('comment').'Config/Table.php';
        foreach ($comment as $name => $sql) {
            if (!$this->is_table_exists($table.$name)) {
                if (dr_count($module['site']) > 1) {
                    // 表示存在多个站
                    foreach ($module['site'] as $sid => $t) {
                        $root = dr_module_table_prefix($dir, $sid).$name;
                        if ($this->is_table_exists($root)) {
                            // 表示已经在其他站创建过了,我们就复制它以前创建的表结构
                            $sql = $this->db->query("SHOW CREATE TABLE `".$this->dbprefix($root)."`")->getRowArray();
                            $sql = str_replace(
                                array($sql['Table'], 'CREATE TABLE'),
                                array('{tablename}', 'CREATE TABLE IF NOT EXISTS'),
                                $sql['Create Table']
                            );
                            break;
                        }
                    }
                }
                $this->db->simpleQuery(str_replace('{tablename}', $table.$name, dr_format_create_sql($sql)));
            }
        }

        // 创建评论字段统计
        if (!$this->db->fieldExists('comments', $table)) {
            $this->query('ALTER TABLE `'.$table.'` ADD `comments` INT(10) DEFAULT 0 COMMENT \'评论数量\'');
        }

        if (!$this->db->fieldExists('avgsort', $table)) {
            $this->query('ALTER TABLE `'.$table.'` ADD `avgsort` decimal(10,2) unsigned DEFAULT \'0.00\' COMMENT \'平均点评分数\'');
        }

        return dr_return_data(1, 'ok');
    }

    // 网站表单里面安装评论
    public function install_form($dir, $siteid) {

        $table = $this->db->table($siteid.'_form')->where('table', $dir)->get()->getRowArray();
        if (!$table) {
            return dr_return_data(0, '网站表单['.$dir.']未安装');
        }

        // 创建评论文件
        $path = dr_get_app_dir('form').'Controllers/';
        $syspath = dr_get_app_dir('comment').'Code/';
        foreach (['Form.php', 'Admin/Form.php', 'Admin/Form_verify.php'] as $file) {
            $nfile = str_replace('Form', ucfirst($dir).'_comment', $file);
            if (!is_file($path.$nfile)) {
                $code = file_get_contents($syspath.$file);
                if (!$code) {
                    return dr_return_data(0, '文件['.$syspath.$file.']读取失败');
                }
                $code = str_replace('{F}', ucfirst($dir), $code);
                $rt = file_put_contents($path.$nfile, $code);
                if (!$rt) {
                    return dr_return_data(0, '文件['.$path.$nfile.']不可写入，创建失败');
                }
            }
        }

        $table = $this->dbprefix($siteid.'_form_'.$dir); // 当前表前缀
        // 创建评论表
        $comment = require dr_get_app_dir('comment').'Config/Table.php';
        foreach ($comment as $name => $sql) {
            if (!$this->is_table_exists($table.$name)) {
                $this->db->simpleQuery(str_replace('{tablename}', $table.$name, dr_format_create_sql($sql)));
            }
        }

        // 创建评论字段统计
        if (!$this->db->fieldExists('comments', $table)) {
            $this->query('ALTER TABLE `'.$table.'` ADD `comments` INT(10) DEFAULT 0 COMMENT \'评论数量\'');
        }

        if (!$this->db->fieldExists('avgsort', $table)) {
            $this->query('ALTER TABLE `'.$table.'` ADD `avgsort` decimal(10,2) unsigned DEFAULT \'0.00\' COMMENT \'平均点评分数\'');
        }

        return dr_return_data(1, 'ok');
    }

    // 表单里面卸载评论
    public function uninstall_form($dir, $siteid) {

        $table = $this->db->table($siteid.'_form')->where('table', $dir)->get()->getRowArray();
        if (!$table) {
            return dr_return_data(0, '网站表单['.$dir.']未安装');
        }

        // 删除评论
        $table = $this->dbprefix($siteid.'_form_'.$dir); // 当前表前缀
        $comment = require dr_get_app_dir('comment').'Config/Table.php';
        foreach ($comment as $name => $sql) {
            $this->db->simpleQuery('DROP TABLE IF EXISTS `'.$table.$name.'`');
        }

        $this->db->table('field')->where('relatedname', 'comment-form-'.$dir)->delete();
        $this->table('admin_menu')->like('mark', 'comment-verify-form-'.$dir)->delete();

        return dr_return_data(1, 'ok');
    }


    // 模块表单里面安装评论
    public function install_mform($dir, $fid, $siteid) {

        $module = $this->db->table('module')->where('dirname', $dir)->get()->getRowArray();
        if (!$module) {
            return dr_return_data(0, '模块['.$dir.']未安装');
        }

        $table = $this->db->table('module_form')->where('module', $dir)->where('table', $fid)->get()->getRowArray();
        if (!$table) {
            return dr_return_data(0, '模块['.$dir.']表单['.$fid.']不存在');
        }

        // 创建评论文件
        $path = dr_get_app_dir($dir).'Controllers/';
        $syspath = dr_get_app_dir('comment').'Code/';
        foreach (['Mform.php', 'Admin/Mform.php', 'Admin/Mform_verify.php'] as $file) {
            $nfile = str_replace('Mform', ucfirst($fid).'_comment', $file);
            if (!is_file($path.$nfile)) {
                $code = file_get_contents($syspath.$file);
                if (!$code) {
                    return dr_return_data(0, '文件['.$syspath.$file.']读取失败');
                }
                $code = str_replace('{F}', ucfirst($fid), $code);
                $rt = file_put_contents($path.$nfile, $code);
                if (!$rt) {
                    return dr_return_data(0, '文件['.$path.$nfile.']不可写入，创建失败');
                }
            }
        }

        $module['site'] = dr_string2array($module['site']);

        $table = $this->dbprefix($siteid.'_'.$dir.'_form_'.$fid); // 当前表前缀
        // 创建评论表
        $comment = require dr_get_app_dir('comment').'Config/Table.php';
        foreach ($comment as $name => $sql) {

            if (!$this->is_table_exists($table.$name)) {
                if (dr_count($module['site']) == 1) {
                    // 表示第一个站就创建
                    $this->db->simpleQuery(str_replace('{tablename}', $table.$name, dr_format_create_sql($sql)));
                } else {
                    // 表示已经在其他站创建过了,我们就复制它以前创建的表结构
                    $old = dr_module_table_prefix($dir, 1).'_form_'.$fid;
                    $sql = $this->db->query("SHOW CREATE TABLE `".$this->dbprefix($old.$name)."`")->getRowArray();
                    $sql = str_replace(
                        array($sql['Table'], 'CREATE TABLE'),
                        array('{tablename}', 'CREATE TABLE IF NOT EXISTS'),
                        $sql['Create Table']
                    );
                    $this->db->simpleQuery(str_replace('{tablename}', $table.$name, dr_format_create_sql($sql)));
                }
            }

        }

        // 创建评论字段统计
        if (!$this->db->fieldExists('comments', $table)) {
            $this->query('ALTER TABLE `'.$table.'` ADD `comments` INT(10) DEFAULT 0 COMMENT \'评论数量\'');
        }

        if (!$this->db->fieldExists('avgsort', $table)) {
            $this->query('ALTER TABLE `'.$table.'` ADD `avgsort` decimal(10,2) unsigned DEFAULT \'0.00\' COMMENT \'平均点评分数\'');
        }

        return dr_return_data(1, 'ok');
    }

    // 模块表单里面卸载评论
    public function uninstall_mform($dir, $fid, $siteid) {

        $rt = $this->table('admin_menu')->like('mark', 'comment-verify-mform-'.$dir.'-'.$fid)->getAll();

        $module = $this->db->table('module')->where('dirname', $dir)->get()->getRowArray();
        if (!$module) {
            return dr_return_data(0, '模块['.$dir.']未安装');
        }

        $table = $this->db->table('module_form')->where('module', $dir)->where('table', $fid)->get()->getRowArray();
        if (!$table) {
            return dr_return_data(0, '模块['.$dir.']表单['.$fid.']不存在');
        }

        // 删除评论
        $comment = require dr_get_app_dir('comment').'Config/Table.php';
        $module['site'] = dr_string2array($module['site']);

        foreach ($module['site'] as $sid => $t) {
            $table = $this->dbprefix(dr_module_table_prefix($dir, $sid).'_form_'.$fid); // 当前表前缀
            foreach ($comment as $name => $sql) {
                $this->db->simpleQuery('DROP TABLE IF EXISTS `'.$table.$name.'`');
            }
        }

        $this->db->table('field')->where('relatedname', 'comment-mform-'.$dir.'-'.$fid)->delete();
        $this->table('admin_menu')->like('mark', 'comment-verify-mform-'.$dir.'-'.$fid)->delete();

        return dr_return_data(1, 'ok');
    }

    // 更新缓存
    public function cache($siteid = SITE_ID) {

        $rt = [];
        $tb = 'app_comment'.($siteid>1 ? $siteid : '');
        if ($siteid > 1) {
            if (!$this->is_table_exists($tb)) {
                // 创建表
                $sql = $this->db->query("SHOW CREATE TABLE `".$this->dbprefix('app_comment')."`")->getRowArray();
                $sql = str_replace(
                    array($sql['Table'], 'CREATE TABLE'),
                    array('{tablename}', 'CREATE TABLE IF NOT EXISTS'),
                    $sql['Create Table']
                );
                $this->db->simpleQuery(str_replace('{tablename}', $this->dbprefix('app_comment'.$siteid), dr_format_create_sql($sql)));
            }
        }

        $data = $this->table($tb)->getAll();
        if ($data) {
            foreach ($data as $m) {
                $value = dr_string2array($m['value']);
                if ($m['name'] == 'module') {
                    $module = \Phpcmf\Service::M('Module')->get_module_info();
                    // 模块内容的评论
                    if ($value) {
                        foreach ($value as $mdir => $cache) {
                            if (!$module[$mdir]) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_table_exists($siteid.'_'.$mdir)) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_table_exists($siteid.'_'.$mdir.'_comment')) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_field_exists($siteid.'_'.$mdir, 'comments')) {
                                unset($value[$mdir]);
                                continue;
                            }
                            $cache['field'] = [];
                            // 模块评论的自定义字段
                            $field = $this->db->table('field')->where('disabled', 0)->where('relatedname', 'comment-module-'.$mdir)->orderBy('displayorder ASC, id ASC')->get()->getResultArray();
                            if ($field) {
                                foreach ($field as $f) {
                                    $f['setting'] = dr_string2array($f['setting']);
                                    $cache['field'][$f['fieldname']] = $f;
                                }
                            }
                            $cache['comment_list_field'] = dr_list_field_order($cache['comment_list_field']);
                            if ($cache['review']['use']) {
                                // 格式化点评
                                if ($cache['review']['value']) {
                                    $tmp = [];
                                    foreach ($cache['review']['value'] as $i => $op) {
                                        $op['name'] && $tmp[$i] = $op['name'];
                                    }
                                    $cache['review']['value'] = $tmp;
                                }
                                if ($cache['review']['option']) {
                                    $tmp = [];
                                    foreach ($cache['review']['option'] as $i => $op) {
                                        $op['use'] && $tmp[$i] = $op['name'];
                                    }
                                    $cache['review']['option'] = $tmp;
                                }
                                unset($cache['review']['use']);
                            } else {
                                $cache['review'] = [];
                            }
                            // 评论菜单写入模块
                            // 入库后台审核菜单
                            $left = $this->db->table('admin_menu')->where('mark', 'content-verify')->get()->getRowArray();
                            if ($left) {
                                $menu = $this->db->table('admin_menu')->where('mark', 'comment-verify-module-'.$mdir)->get()->getRowArray();
                                $save = [
                                    'uri' => $mdir.'/comment_verify/index',
                                    'mark' => 'comment-verify-module-'.$mdir,
                                    'name' => $menu && $menu['name'] ? $menu['name'] : dr_lang('%s%s', $module[$mdir]['name'], dr_comment_cname($cache['cname'])),
                                    'icon' => 'fa fa-comments',
                                    'displayorder' => $menu ? intval($menu['displayorder']) : '-1',
                                ];
                                $menu ? \Phpcmf\Service::M('menu')->_edit('admin', $menu['id'], $save) : \Phpcmf\Service::M('menu')->_add('admin', $left['id'], $save);
                            }

                            $value[$mdir] = $cache;
                        }
                    }
                } elseif ($m['name'] == 'form' && dr_is_app('form')) {
                    // 网站表单的评论
                    $row = $this->table($siteid.'_form')->getAll();
                    if ($value && $row) {
                        $form = [];
                        foreach ($row as $t) {
                            $form[$t['table']] = $t;
                        }
                        foreach ($value as $mdir => $cache) {
                            if (!$value[$mdir]) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_table_exists($siteid.'_form_'.$mdir)) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_table_exists($siteid.'_form_'.$mdir.'_comment')) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_field_exists($siteid.'_form_'.$mdir, 'comments')) {
                                unset($value[$mdir]);
                                continue;
                            }
                            $cache['field'] = [];
                            // 评论的自定义字段
                            $field = $this->db->table('field')->where('disabled', 0)->where('relatedname', 'comment-form-'.$mdir)->where('relatedid', $siteid)->orderBy('displayorder ASC, id ASC')->get()->getResultArray();
                            if ($field) {
                                foreach ($field as $f) {
                                    $f['setting'] = dr_string2array($f['setting']);
                                    $cache['field'][$f['fieldname']] = $f;
                                }
                            }
                            $cache['comment_list_field'] = dr_list_field_order($cache['comment_list_field']);
                            if ($cache['review']['use']) {
                                // 格式化点评
                                if ($cache['review']['value']) {
                                    $tmp = [];
                                    foreach ($cache['review']['value'] as $i => $op) {
                                        $op['name'] && $tmp[$i] = $op['name'];
                                    }
                                    $cache['review']['value'] = $tmp;
                                }
                                if ($cache['review']['option']) {
                                    $tmp = [];
                                    foreach ($cache['review']['option'] as $i => $op) {
                                        $op['use'] && $tmp[$i] = $op['name'];
                                    }
                                    $cache['review']['option'] = $tmp;
                                }
                                unset($cache['review']['use']);
                            } else {
                                $cache['review'] = [];
                            }
                            // 入库后台审核菜单
                            $left = $this->db->table('admin_menu')->where('mark', 'content-verify')->get()->getRowArray();
                            if ($left) {
                                $menu = $this->db->table('admin_menu')->where('mark', 'comment-verify-form-'.$mdir)->get()->getRowArray();
                                $save = [
                                    'uri' => 'form/'.$mdir.'_comment_verify/index',
                                    'mark' => 'comment-verify-form-'.$mdir,
                                    'name' => $menu && $menu['name'] ? $menu['name'] : dr_lang('%s%s', $form[$mdir]['name'], dr_comment_cname($cache['cname'])),
                                    'icon' => 'fa fa-comments',
                                    'displayorder' => $menu ? intval($menu['displayorder']) : '-1',
                                ];
                                $menu ? \Phpcmf\Service::M('menu')->_edit('admin', $menu['id'], $save) : \Phpcmf\Service::M('menu')->_add('admin', $left['id'], $save);
                            }
                            $value[$mdir] = $cache;
                        }
                    }
                } elseif ($m['name'] == 'mform' && dr_is_app('mform')) {
                    // 模块表单的评论
                    $row = $this->table('module_form')->getAll();
                    if ($value && $row) {
                        $form = [];
                        foreach ($row as $t) {
                            $t['tablename'] = \Phpcmf\Service::M()->dbprefix($siteid.'_'.$t['module'].'_form_'.$t['table']);
                            $form[$t['module'].'-'.$t['table']] = $t;
                        }
                        foreach ($value as $mdir => $cache) {
                            if (!$value[$mdir]) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_table_exists($form[$mdir]['tablename'])) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_table_exists($form[$mdir]['tablename'].'_comment')) {
                                unset($value[$mdir]);
                                continue;
                            } elseif (!$this->is_field_exists($form[$mdir]['tablename'], 'comments')) {
                                unset($value[$mdir]);
                                continue;
                            }
                            $cache['field'] = [];
                            // 模块评论的自定义字段
                            $field = $this->db->table('field')->where('disabled', 0)->where('relatedname', 'comment-mform-' . $mdir)->orderBy('displayorder ASC, id ASC')->get()->getResultArray();
                            if ($field) {
                                foreach ($field as $f) {
                                    $f['setting'] = dr_string2array($f['setting']);
                                    $cache['field'][$f['fieldname']] = $f;
                                }
                            }
                            $cache['comment_list_field'] = dr_list_field_order($cache['comment_list_field']);
                            if ($cache['review']['use']) {
                                // 格式化点评
                                if ($cache['review']['value']) {
                                    $tmp = [];
                                    foreach ($cache['review']['value'] as $i => $op) {
                                        $op['name'] && $tmp[$i] = $op['name'];
                                    }
                                    $cache['review']['value'] = $tmp;
                                }
                                if ($cache['review']['option']) {
                                    $tmp = [];
                                    foreach ($cache['review']['option'] as $i => $op) {
                                        $op['use'] && $tmp[$i] = $op['name'];
                                    }
                                    $cache['review']['option'] = $tmp;
                                }
                                unset($cache['review']['use']);
                            } else {
                                $cache['review'] = [];
                            }
                            // 评论菜单写入模块
                            // 入库后台审核菜单
                            list($mid, $fid) = explode('-', $mdir);
                            $left = $this->db->table('admin_menu')->where('mark', 'content-verify')->get()->getRowArray();
                            if ($left) {
                                $menu = $this->db->table('admin_menu')->where('mark', 'comment-verify-mform-'.$mdir.'')->get()->getRowArray();
                                $save = [
                                    'uri' => $mid.'/'.$fid.'_comment_verify/index',
                                    'mark' => 'comment-verify-mform-'.$mdir,
                                    'name' => $menu && $menu['name'] ? $menu['name'] : dr_lang('%s%s', $form[$mdir]['name'], dr_comment_cname($cache['cname'])),
                                    'icon' => 'fa fa-comments',
                                    'displayorder' => $menu ? intval($menu['displayorder']) : '-1',
                                ];
                                $menu ? \Phpcmf\Service::M('menu')->_edit('admin', $menu['id'], $save) : \Phpcmf\Service::M('menu')->_add('admin', $left['id'], $save);
                            }

                            $value[$mdir] = $cache;
                        }
                    }
                }
                $rt[$m['name']] = $value;
            }
        }

        \Phpcmf\Service::L('cache')->set_file('app-comment-'.$siteid, $rt);
    }

    // 初始化模块
    public function _init($mdb, $comment) {
        $this->siteid = max(1, (int)$mdb->siteid);
        $this->mdb = $mdb;
        $this->mytable = $mdb->mytable;
        $this->comment = $comment;
        $this->dirname = $mdb->dirname;
        return $this;
    }

    // 获取评论索引数据
    public function get_comment_index($cid) {

        if (!$cid) {
            return [];
        }

        $rt = $this->table($this->mytable.'_comment_index')->where('cid', $cid)->getRow();
        if (!$rt) {
            // 不存在就创建它
            $rt = [
                'cid' => $cid,
                'sort1' => 0,
                'sort2' => 0,
                'sort3' => 0,
                'sort4' => 0,
                'sort5' => 0,
                'sort6' => 0,
                'sort7' => 0,
                'sort8' => 0,
                'sort9' => 0,
                'oppose' => 0,
                'support' => 0,
                'avgsort' => 0,
                'comments' => 0,
            ];
            $rt['id'] = $this->table($this->mytable.'_comment_index')->insert($rt);
        }

        return $rt;
    }

    // 提交评论
    // $value 主题信息和回复人；$data评论内容和点评内容；$my自定义字段
    public function insert_comment($value, $data, $my = []) {

        $insert = [];
        $insert['cid'] = (int)$value['index']['id'];
        $insert['cuid'] = (int)$value['index']['uid'];
        //$insert['catid'] = (int)$value['index']['catid'];
        $insert['uid'] = (int)$value['member']['uid'];
        $insert['reply'] = (int)$value['reply_id'];
        $insert['in_reply'] = 0;
        $insert['status'] = $value['status'];
        $insert['author'] = $value['member']['uid'] ? ($value['member']['name'] ? $value['member']['name'] : $value['member']['username']) : '游客';
        $insert['content'] = $data['content'];
        $insert['support'] = $insert['oppose'] = $insert['avgsort'] = 0;
        $insert['inputip'] = \Phpcmf\Service::L('input')->ip_info();
        $insert['inputtime'] = $data['inputtime'] ? $data['inputtime'] : SYS_TIME;
        //$insert['orderid'] = (int)$value['orderid'];

        // 点评选项值
        $_value = [];
        $_avgsort = 0;
        for ($i = 1; $i <= 9; $i++) {
            $insert['sort'.$i] = isset($data['review'][$i]) ? (int)$data['review'][$i] : 0;
            $_avgsort+= $insert['sort'.$i];
            $insert['sort'.$i] && $_value[$i] = $insert['sort'.$i];
        }

        if ($_avgsort) {
            // 算法类别
            $dl = empty($this->comment['review']['point']) || $this->comment['review']['point'] < 0 ? 0 : $this->comment['review']['point']; //小数点位数
            // 分别计算各个选项分数
            $insert['avgsort'] = round(($_avgsort / dr_count($_value)), $dl);
        }

        // 自定义字段入库
        $my && $insert = array_merge($insert, $my);

        $rt = $this->table($this->mytable.'_comment')->insert($insert);
        if (!$rt['code']) {
            return $rt;
        }

        // 评论成功返回id
        $id = $rt['code'];

        if (!$insert['status']) {
            // 需要审核时直接返回
            \Phpcmf\Service::M('member')->admin_notice($this->siteid, 'content', \Phpcmf\Service::C()->member, dr_lang('%s: 新%s审核', MODULE_NAME, dr_comment_cname($this->comment['cname'])), $this->dirname.'/comment_verify/edit:cid/'.$insert['cid'].'/id/'.$id);
            return dr_return_data($id, 'verify');
        } else {
            // 直接通过的评论
            $insert['id'] = $id;
            $this->verify_comment($insert);
            return dr_return_data($id, 'ok');
        }

    }

    // 审核评论
    public function verify_comment($row) {

        if (!$row) {
            return;
        }

        $id = (int)$row['id'];

        // 当前是未审核状态时才更新状态
        if ($row['status'] != 1) {
            // 变更审核状态
            $this->db->table($this->mytable.'_comment')->where('id', $id)->update(['status' => 1]);
        }

        // 提醒
        /* 暂时不要回复站内信通知
        $row['reply']
            ? \Phpcmf\Service::M('member')->notice($row['uid'], 2, dr_lang('评论被人回复'), '/index.php?s='.MOD_DIR.'&c=show&id='.$row['cid'])
            : \Phpcmf\Service::M('member')->notice($row['cuid'], 2, dr_lang('收到了新的评论'), '/index.php?s='.MOD_DIR.'&c=show&id='.$row['cid']);
        */

        // 统计评论总数
        $this->comment_update_total($row);

        // 回复评论时，将主题设置为存在回复状态
        $row['reply'] && $this->table($this->mytable.'_comment')->update($row['reply'], ['in_reply' => 1]);

        // 增减金币
        $score = \Phpcmf\Service::C()->_get_auth_value('comment_score', dr_member_info($row['uid']));
        $score && \Phpcmf\Service::M('member')->add_score($row['uid'], $score, dr_lang('%s发布%s', MODULE_NAME, dr_comment_cname(\Phpcmf\Service::C()->module['comment']['cname'])), $row['curl']);

        // 增减经验
        $exp = \Phpcmf\Service::C()->_get_auth_value('comment_exp', dr_member_info($row['uid']));
        $exp && \Phpcmf\Service::M('member')->add_experience($row['uid'], $exp, dr_lang('%s发布%s', MODULE_NAME, dr_comment_cname($this->comment['cname'])), $row['curl']);

        // 更新评分
        $this->comment_update_review($row);

        // 执行通知
        \Phpcmf\Service::M('member')->todo_admin_notice($this->dirname.'/comment_verify/edit:cid/'.$row['cid'].'/id/'.$row['id'], $this->siteid);

        // 获取文章标题
        $index = $this->table($this->mytable)->get($row['cid']);
        $row['title'] = $index['title'];
        $row['index'] = $index;
        $row['comment_uid'] = $row['uid'];
        $row['comment_author'] = $row['author'];

        // 挂钩点 评论完成之后
        \Phpcmf\Hooks::trigger('comment_after', $row);

        // 运行自定义的回调后的函数
        if (method_exists($this->mdb, '_comment_after')) {
            call_user_func(array($this->mdb, '_comment_after'), $row);
        }

        // 评论通过后的通知消息
        $row['url'] = $index['url'];
        \Phpcmf\Service::L('Notice')->send_notice('module_'.$this->dirname.'_comment_verify_1', $row);

        // 评论后通知内容作者
        $row['uid'] = $index['uid'];
        \Phpcmf\Service::L('Notice')->send_notice('module_'.$this->dirname.'_comment_verify_2', $row);

        \Phpcmf\Service::L('cache')->clear('module_'.$this->dirname.'_show_id_'.$row['cid']);
    }

    // 获取评论列表
    public function get_comment_result($cid, $order, $page, $pagesize, $total, $field) {

        if (!$cid) {
            return [];
        }

        $list = $this->db->table($this->mytable.'_comment')
            ->where('cid', $cid)->where('reply', 0)->where('status', 1)
            ->limit($pagesize, $pagesize * ($page - 1))
            ->orderBy($order)
            ->get()->getResultArray();

        if ($list) {
            $dfield = \Phpcmf\Service::L('Field')->app($this->dirname);
            foreach ($list as $i => $t) {
                $reply = !$t['in_reply'] ? [] : $this->db->table($this->mytable.'_comment')
                    ->where('cid', $cid)->where('reply', $t['id'])->where('status', 1)
                    ->orderBy($order)
                    ->get()->getResultArray();
                if ($field) {
                    // 格式化显示自定义字段内容
                    $list[$i] = $dfield->format_value($field, $t, 1);
                    if ($reply) {
                        foreach ($reply as $b => $v) {
                            $reply[$b] = $dfield->format_value($field, $v, 1);
                        }
                    }
                }
                $list[$i]['rlist'] = $reply;
            }
        }


        !$total && $total = $this->db->table($this->mytable.'_comment')->where('cid', $cid)->where('reply', 0)->where('status', 1)->countAllResults();

        return [$list, $total];
    }


    // 删除评论
    public function delete_comment($id, $cid = 0) {

        if (!$id) {
            return 0;
        }

        $data = $this->table($this->mytable.'_comment')->get($id);
        if (!$data) {
            return -1;
        }

        // 删除评论数据
        $this->db->table($this->mytable.'_comment')->where('id', $id)->delete();
        $this->db->table($this->mytable.'_comment')->where('reply', $id)->delete();


        // 统计评论总数
        $this->comment_update_total($data);

        // 删除附件
        SYS_ATTACHMENT_DB  && \Phpcmf\Service::M('Attachment')->id_delete(
            $data['uid'],
            [$id],
            $this->dbprefix($this->mytable.'_comment-'.($data['reply'] ? $data['reply'] : $id))
        );

        // 更新评分
        $this->comment_update_review($data);

        return 1;
    }

    // 更新统计
    public function comment_update_total($row) {

        if (!\Phpcmf\Service::C()->module['comment'] || !$row) {
            return;
        }

        $cid = (int)$row['cid'];
        // 统计评论总数
        if (!\Phpcmf\Service::C()->module['comment']['ct_reply']) {
            $total = $this->db->table($this->mytable.'_comment')->where('cid', $cid)->where('reply', 0)->where('status', 1)->countAllResults();
        } else {
            $total = $this->db->table($this->mytable.'_comment')->where('cid', $cid)->where('status', 1)->countAllResults();
        }

        $this->table($this->mytable)->update($cid, ['comments' => $total]);
        $this->table($this->mytable.'_comment_index')->update($row['id'], ['comments' => $total]);

    }

    // 更新评分
    public function comment_update_review($row) {

        // 只在开启时更新
        if (!\Phpcmf\Service::C()->module['comment']['review']) {
            return;
        }

        $id = (int)$row['id'];
        $cid = (int)$row['cid'];

        // 更新点评数据
        $review = $set = [];
        $_avgsort = 0;
        for ($i = 1; $i <= 9; $i++) {
            if ($row['sort'.$i]) {
                $review[$i] = $row['sort'.$i];
                $set['sort'.$i] = 0;
                $_avgsort += $review[$i];
            }
        }

        // 分值不存在时不更新
        if (!$review) {
            return ;
        }

        // 统计总的点评数
        $builder = $this->db->table($this->mytable.'_comment');
        $builder->where('cid', $cid);
        $builder->selectSum('status', 'num');
        foreach($review as $i => $val) {
            $builder->selectSum('sort'.$i);
        }

        // 不统计回复
        if (!\Phpcmf\Service::C()->module['comment']['ct_reply']) {
            $builder->where('reply', 0);
        }

        $grade = $builder->where('status', 1)->get()->getRowArray();

        if (!$grade) {
            return;
        }

        // 算法类别
        $st = round((int)$this->comment['review']['score'] / 5); //显示分数制 5分，10分，百分
        $dl = empty($this->comment['review']['point']) || $this->comment['review']['point'] < 0 ? 0 : $this->comment['review']['point']; //小数点位数

        // 分别计算各个选项分数
        foreach($review as $i => $aaaaa) {
            $flag = 'sort'.$i;
            $set[$flag] = $grade[$flag] ? round( ($grade[$flag] / $grade['num'] * $st), $dl) : 0;
            $set['avgsort']+= $set[$flag];
        }

        // 总表的平均分
        $set['avgsort'] = round(($set['avgsort'] / dr_count($review)), $dl);

        // 本记录的
        $avgsort = round(($_avgsort / dr_count($review) * $st), $dl);

        // 更新到索引表
        $this->db->table($this->mytable.'_comment')->where('id', $id)->update(['avgsort' => $avgsort]);

        // 更新到关联主表
        $this->table($this->mytable)->update($cid, [
            'avgsort' => $set['avgsort'],
        ]);

        // 更新到索引表
        $this->db->table($this->mytable.'_comment_index')->where('cid', $cid)->update($set);

    }

    // 评论地址
    public function comment_url($id, $mid = '') {

        // 模块目录识别
        defined('MOD_DIR') && MOD_DIR && $dir = MOD_DIR;
        $mid && $dir = $mid;

        $module = \Phpcmf\Service::L('cache')->get('module-' . SITE_ID . '-' . $dir);

        return dr_url_prefix(\Phpcmf\Service::L('router')->url_prefix('php', $module, [], SITE_FID) . 'c=comment&id=' . $id);
    }

}